import { createRouter, createWebHistory } from 'vue-router';
import AddDish from '../components/AddDish.vue';
import EditDish from '../components/EditDish.vue';
import DishesList from '../components/DishesList.vue';
import RateDish from '../components/RateDish.vue';
import MealPlan from '../components/MealPlan.vue';
import WeekMenu from '../components/WeekMenu.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: WeekMenu
  },
  {
    path: '/AddDish',
    name: 'AddDish',
    component: AddDish,
    meta: { requiresAuth: true, role: 'admin' }
  },
  {
    path: '/dishes',
    name: 'DishesList',
    component: DishesList,
    meta: { requiresAuth: true, role: 'admin' }
  },
  {
    path: '/edit/:id?',
    name: 'EditDish',
    component: EditDish,
    meta: { requiresAuth: true, role: 'admin' }
  },
  {
    path: '/rate/:dish_id?',
    name: 'RateDish',
    component: RateDish,
    props: true
  },
  {
    path: '/meal-plan',
    name: 'MealPlan',
    component: MealPlan,
    meta: { requiresAuth: true, role: 'admin' }
  },
  {
    path: '/week-menu',
    name: 'WeekMenu',
    component: WeekMenu
  },
  { path: '/:pathMatch(.*)*', redirect: '/' } // 其他未匹配的路由重定向到默认路由
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局导航守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true';
  const userRole = localStorage.getItem('userRole');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({ path: '/' });
    } else {
      const requiredRole = to.meta.role;
      if (requiredRole && requiredRole !== userRole) {
        next({ path: '/' });
      } else {
        next();
      }
    }
  } else {
    next();
  }
});

export default router;